/************************************************************************/
// Copyright (C) 2016, han_gangbiao. All rights reserved.
// Use of this source code is governed by a GPL-v2 license that can be found in the License file.
// 
// [Time]:      2016-1-4 21:53:17
// [Author]:    han_gangbiao [http://my.oschina.net/jackhen]
// [Info]:      
/************************************************************************/

#include "netdata.h"

netdata_t::netdata_t() : m_data(NULL), m_len(0), m_cap(0)
{
	assign("", 0);
}

netdata_t::netdata_t(const char* data, int len) : m_data(NULL), m_len(0), m_cap(0)
{
	assign(data, len);
}

netdata_t::~netdata_t()
{
	delete [] m_data, m_data = NULL;
	m_cap = m_len = 0;
}

int netdata_t::reserve(int len)
{
	if(len <= 0)
		return -1;
	if(len <= m_cap)
		return m_cap;

	int newlen = m_cap*2;
	if(newlen < len)
		newlen = len;
	char* str = new char[newlen];
	if(m_len > 0)
		memcpy(str, m_data, m_len);
	str[m_len] = '\0';
	if(m_cap > 0)
		delete [] m_data;
	m_data = str;
	m_cap = newlen;
	return m_cap;
}

netdata_t& netdata_t::assign(const char* data, int len)
{
	if( data == NULL || len < 0 )
		return *this;
	if( m_data == data )
		return *this;

	int buflen, datalen; // the require buf len and actual data len
	buflen = len + 1;
	datalen = len;

	m_len = 0;
	reserve(buflen);
	if( datalen > 0 )
		memcpy(m_data, data, datalen);
	m_data[datalen] = '\0';
	m_len = datalen;

	return *this;
}

netdata_t& netdata_t::append(const char* data, int len)
{
	if( data == NULL || len <= 0 )
		return *this;

	int buflen, datalen; // the require buf len and actual data len
	buflen = len + 1;
	datalen = len;

	reserve( m_len + buflen );
	if( datalen > 0 )
		memcpy(m_data+m_len, data, datalen);
	m_data[m_len + datalen] = '\0';
	m_len += datalen;

	return *this;
}

